package com.mobilezu.mobile.common.dao.hibernate;

import java.util.List;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.mobilezu.mobile.common.dao.SystemUserDaoable;
import com.mobilezu.mobile.common.model.SystemUser;
import com.mobilezu.mobile.pushserver.service.UserNotFoundException;

@SuppressWarnings({ "unchecked", "rawtypes" })
public class SystemUserDaoHibernate extends HibernateDaoSupport implements
		SystemUserDaoable {


	public boolean exists(Long id) {
		SystemUser systemUser = (SystemUser) getHibernateTemplate().get(
				SystemUser.class, id);
		return systemUser != null;
	}

	@Override
	public SystemUser getSystemUser(Long id) {
		return (SystemUser) getHibernateTemplate().get(SystemUser.class, id);
	}

	@Override
	public SystemUser saveSystemUser(SystemUser systemUser) {
		getHibernateTemplate().saveOrUpdate(systemUser);
		getHibernateTemplate().flush();
		return systemUser;
	}

	@Override
	public void removeSystemUser(Long id) {
		getHibernateTemplate().delete(getSystemUser(id));
		
	}

	@Override
	public List<SystemUser> getSystemUsers() {
		return getHibernateTemplate().find("from SystemUser u order by u.updatedDate desc");
	}

	@Override
	public SystemUser getSystemUserByUsername(String username)
			throws UserNotFoundException {
		HibernateTemplate template=getHibernateTemplate();
		List systemUsers =template.find("from SystemUser where username=?", username);
		if (systemUsers == null || systemUsers.isEmpty()) {
			throw new UserNotFoundException("User '" + systemUsers
					+ "' not found");
		} else {
			return (SystemUser) systemUsers.get(0);
		}
	}

}
